<template>
  <div class="page-content center-center">
    <div>
      <div class="title-info text-left">
        基本信息（必填）
      </div>
      <el-form :model="modelForm" ref="modelForm" label-width="100px" class="demo-ruleForm ">
      <div class="center-center">

        <div class="w-100p">
          <el-form-item label=" " prop="name" :rules="[{ required: true, message: '角色不能为空', trigger: 'blur' }]">
            <el-input placeholder="请输入角色名称" v-model="modelForm.name" size="medium" :maxLength="20">
              <template slot="prepend">
                <el-tooltip placement="top" content="请填写角色名称">
                  <el-button tabIndex="-1">角色名称</el-button>
                </el-tooltip>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label=" " prop="type" :rules="[{ required: true, message: '角色类型不能为空', trigger: 'blur' }]">
            <div class="el-input el-input-group el-input-group--prepend">
              <div class="el-input-group__prepend">角色类型</div>
              <el-select v-model="modelForm.type" filterable placeholder="请选择角色类型" :disabled="!isSave" @change="changeType" size="medium" class="w-100p">
                <el-option
                  v-for="item in roleList"
                  :key="item.key"
                  :label="item.text"
                  :value="item.key">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </div>



      </div>
      <div class="title-info text-left">
        功能权限分配
      </div>
      <div class="center-center">
        <div>

          <el-tabs v-model="activeName">
            <el-tab-pane v-if="modelForm.type == 'CHAINROLE'" label="连锁后台功能权限" name="chain">连锁后台功能权限</el-tab-pane>
            <el-tab-pane v-if="modelForm.type == 'BRANCHROLE'" label="门店后台功能权限" name="branch_back">门店后台功能权限</el-tab-pane>
            <el-tab-pane v-if="modelForm.type == 'BRANCHROLE'" label="收银权限" name="branch_front">收银权限</el-tab-pane>
          </el-tabs>


         <!-- <el-form-item v-if="modelForm.type == 'CHAINROLE'">
            <div class="el-input el-input-group el-input-group&#45;&#45;prepend" >
              <div class="el-input-group__prepend">连锁功能权限</div>
              <el-tree style="overflow-y: auto;max-height: 300px;"
                       :data="permissions"
                       show-checkbox
                       :show-all-levels="false"
                       default-expand-all
                       node-key="id"
                       ref="permissionTree"
                       :default-checked-keys="defaultPermissionChecked"
                       highlight-current
                       :props="defaultProps">
              </el-tree>
            </div>
          </el-form-item>-->

          <!--<div v-if="modelForm.type == 'BRANCHROLE'">
            <el-form-item>
              <div class="el-input el-input-group el-input-group&#45;&#45;prepend" >
                <div class="el-input-group__prepend">门店后台权限</div>
                <el-tree style="overflow-y: auto;max-height: 300px;"
                         :data="branchBackPermissions"
                         show-checkbox
                         :show-all-levels="false"
                         default-expand-all
                         node-key="id"
                         ref="branchBackPermissionTree"
                         :default-checked-keys="defaultBackPermissionChecked"
                         highlight-current
                         :props="defaultProps">
                </el-tree>
              </div>
            </el-form-item>

            <el-form-item>
              <div class="el-input el-input-group el-input-group&#45;&#45;prepend" >
                <div class="el-input-group__prepend">收银权限</div>
                <el-tree style="overflow-y: auto;max-height: 300px;"
                         :data="branchFrontPermissions"
                         show-checkbox
                         :show-all-levels="false"
                         default-expand-all
                         node-key="id"
                         ref="branchFrontPermissionTree"
                         :default-checked-keys="defaultFrontPermissionChecked"
                         highlight-current
                         :props="defaultProps">
                </el-tree>
              </div>
            </el-form-item>
          </div>-->
        </div>

      </div>
      </el-form>

    </div>
  </div>
</template>
<script>
  //注意路径
  export default {
    data() {
      return {
        activeName:"chain",
        modelForm: {},
        downCategeryId:[],
        treeData:[],
        showDialog: false,
        activityId: "",
        isSave: true,
        treeShow: false,
        settlemements: [],
        states: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        departList:[],     //部门list
        permissions:[],   //功能list
        disableData:[] ,    //可管理list
        defaultChecked:[],  //可管理默认全部选中
        defaultPermissionChecked:[],
        roleList:[],//角色类型
        branchBackPermissions:[],//门店后台功能权限
        branchFrontPermissions:[],//门店收银权限
        defaultBackPermissionChecked:[],
        defaultFrontPermissionChecked:[],
        id:''
      };
    },
    created() {
      window.this = this;
      if(this.$route.query.id && this.$route.query.id!='undefined'){
        this.id = this.$route.query.id;
      }
      this.initData();
    },
    methods: {

      initData(){
        if (this.id != '') {
          this.activityId = this.id;
          this.isSave = false;
          this.$axios.get("organization/positions/" + this.activityId + "/update").then(data => {
            this.modelForm=data.content.position;
            var per = data.content.permissions;
            this.newLabel(per);
            this.permissions = per;
            this.defaultPermissionChecked=data.content.rolePermission;
            this.roleList = data.content.roleList;
            var branchBackPermissions = data.content.branchBackPermissions;
            this.newLabel(branchBackPermissions);
            this.branchBackPermissions = branchBackPermissions;
            var branchFrontPermissions = data.content.branchFrontPermissions;
            this.newLabel(branchFrontPermissions);
            this.branchFrontPermissions = branchFrontPermissions;

            this.defaultBackPermissionChecked = data.content.branchCheckBackPermissions;
            this.defaultFrontPermissionChecked = data.content.branchCheckFrontPermissions;

          });
        } else {
          this.isSave = true;
          this.$axios.get("organization/positions/create").then(data => {
            this.downCategeryId=[];
            var tree = data.content.districts;
            this.newLabel(tree);
            this.treeData = tree;
            var permiss=data.content.permissions;
            this.newLabel(permiss);
            this.permissions=permiss;

            var branchBackPermissions = data.content.branchBackPermissions;
            this.newLabel(branchBackPermissions);
            this.branchBackPermissions = branchBackPermissions;
            var branchFrontPermissions = data.content.branchFrontPermissions;
            this.newLabel(branchFrontPermissions);
            this.branchFrontPermissions = branchFrontPermissions;

            this.disableData=[];
            this.defaultChecked=[];
            this.roleList = data.content.roleList;
            this.modelForm=data.content.position;
          });
        }
      },
      //切换角色类型
      changeType(val){
        if(val=='CHAINROLE'){

        }else if(val=='BRANCHROLE'){

        }
        console.log(val);
      },

      changeData(){
        this.getDepart();
      },
      getDepart(){
        var item=this.downCategeryId[this.downCategeryId.length-1];
        if(!item){
          item=this.treeData[0].id;
        }
        this.$axios.get("organization/districts/getDepartment?id="+item).then(res=>{
          if(res.success){
            this.departList=[];
            this.departList=res.content.departmentList;
            if(res.content.type=='district'){
              var dis=res.content.districtList;
              this.newLabel(dis);
              this.disableData=dis;
            }else{
              var dis=res.content.branchList;
              this.newLabel(dis);
              this.disableData=dis;
            }
            if(this.isSave){
              for(var i=0;i<this.disableData.length;i++){
                this.defaultChecked.push(this.disableData[i].value);    //默认选中全部,新建的时候
              }
            }
          }
        },res=>{})
      },
      newLabel(newList) {
        if (newList) {
          for (var i = 0; i < newList.length; i++) {
            newList[i].label = newList[i].name;
            newList[i].value = newList[i].id + "";
            if (!newList[i].children ||  newList[i].children.length == 0) {
              newList[i].children = null;
            } else {
              for (var s = 0; s < newList[i].children.length; s++) {
                newList[i].children[s].label = newList[i].children[s].name;
                newList[i].children[s].value = newList[i].children[s].id + "";
                this.newLabel(newList[i].children);    //再次循环
              }
            }
          }
        }
      },
      goBack() {
        this.router.go(-1);
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(this.modelForm);
//            this.modelForm.attachDistrictId=this.downCategeryId[this.downCategeryId.length-1];  //所属区域

//            var disPermission=this.$refs.disableTree.getCheckedKeys();
//            if(disPermission.length>0){
//              this.modelForm.attachDataPermission=JSON.stringify(disPermission);
//            }else{
//              this.modelForm.attachDataPermission=[];
//            }


            if(this.modelForm.type=='CHAINROLE'){
              console.log(this.modelForm);
              var permissions=this.$refs.permissionTree.getCheckedKeys();
              if(permissions.length>0){   //功能权限字符串
                this.modelForm.permissions=JSON.stringify(permissions);
              }else{
                this.modelForm.permissions=[];
              }
              this.modelForm.branchBackPermissions=[];
              this.modelForm.branchFrontPermissions = [];
            }else if(this.modelForm.type == 'BRANCHROLE'){
              console.log(this.modelForm);
              var branchBackPermissions = this.$refs.branchBackPermissionTree.getCheckedKeys();
              if(branchBackPermissions.length>0){
                this.modelForm.branchBackPermissions = JSON.stringify(branchBackPermissions);
              }else{
                this.modelForm.branchBackPermissions = [];
              }
              var branchFrontPermissions = this.$refs.branchFrontPermissionTree.getCheckedKeys();
              if(branchFrontPermissions.length>0){
                this.modelForm.branchFrontPermissions = JSON.stringify(branchFrontPermissions);
              }else {
                this.modelForm.branchFrontPermissions = [];
              }
              this.modelForm.permissions=[];
            }

            if (this.isSave) {
              this.$axios.post("organization/positions/create",this.modelForm,"json").then(data => {
                if (data.status == 200) {
                  this.$message({
                    message: data.message,
                    type: 'success'
                  });
                  this.$emit('addSuccess');
                } else {
                  this.$message.error(data.message);
                }
              })
            } else {
              this.modelForm._method = "PUT";
              this.$axios.put("organization/positions/" + this.activityId + "/update",this.modelForm,"json").then(data => {
                if (data.status == 200) {
                  this.$message({
                    message: data.message,
                    type: 'success'
                  });
                  this.$emit('addSuccess');
                              this.$refs[formName].resetFields();
                              this.defaultChecked=[];
                } else {
                  this.$message.error(data.message);
                }
              })
            }
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.defaultChecked=[];
        this.$refs[formName].resetFields();
        this.$emit('close');
        this.showDialog = false;
      },
      handleClose(done) {
        this.$emit('close');
        done();
      },
      isNum(item, key) {
        var r = /^\+?[1-9][0-9]*$/;
        if (!r.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      },
      isDouble(item, key) {
        var isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = item[key]
        }
      }
    }
  }
</script>
<style scoped>
  .el-input-group--append .el-input__inner, .el-input-group__prepend {
    border-top-left-radius: 0 !important;
    border-bottom-left-radius: 0 !important;
  }
  .addRole{
    background-color: #ffffff;
    height: 80vh;
    margin:10px;
  }

  .title-info {
    background-color: #F8F8F8;
    border: 1px solid #e4e4e4;
    color: #23c6c8;
    font-weight: bold;
    padding: 10px;
    margin-bottom: 20px;
    width: 800px;
  }
</style>
